package org.lh.ibernate.core.impl;

import org.lh.ibernate.annotation.Table;
import org.lh.ibernate.core.*;
import org.lh.ibernate.core.tools.ParameterLink;
import org.lh.ibernate.utils.impl.DbUtil;
import org.lh.ibernate.utils.IDbUtil;

import java.sql.ResultSet;
import java.util.List;

//一个用于操作数据库crud的工具对象
public class SessionUtil<T,PK> implements ISessionUtil<T,PK> {

    private IFieldHandle iFieldHandle=new FieldHandle();
    private IResultSetHandler iResultSetHandler;
    private ICacheHandle iCacheHandle;
    private IQuery<T,PK> iQuery=new QueryUtil<T,PK>();
    private IDelete<T,PK> iDelete=new DeleteUtil<T,PK>();
    private IInsert<T> iInsert=new InsertUtil<T>();
    private IUpdate<T,PK> iUpdate=new UpdateUtil<T,PK>();
    private IDbUtil iDbUtil=new DbUtil();
    private  Class<T> clazz;
    public SessionUtil(Class<T> clzz){
        clazz=  clzz;
    }


    @Override
    public void save(T obj) throws Exception {
        iInsert.save(obj);
    }

    @Override
    public void update(Object obj,PK pk) throws Exception {
        iUpdate.update(obj, pk);
    }

    @Override
    public void delete(Class<T> clazz,PK pk) throws Exception {
        iDelete.delete(clazz, pk);
    }


    @Override
    public T findOne(T obj, PK pk) throws Exception {
        Class clazz=obj.getClass();
        iCacheHandle=new CaCheHandle();
        if(iCacheHandle.isSupportCache(clazz)){ //处理缓存的处理
            if(iCacheHandle.isContainCacheKey(clazz)){
                obj=iQuery.findObjFromRedis(pk);
                if(obj!=null){
                    return obj;
                }
            }else{
                throw new Exception("缺少@cacheKey注解");
            }
        }
        boolean tableNameExist=clazz.isAnnotationPresent(Table.class);
        if(tableNameExist) {
            obj=(T) iQuery.findOneObjBySql(clazz, pk);
            //同时将数据存储到redis里面去

            return obj;
        }
        return null;
    }


    @Override
    public List<T> findAll(Class<T> clazz) throws Exception {
        return iQuery.findAllBySql(clazz);
    }

    //供外界开发调用的自定义查询接口
    @Override
    public List<T> queryCustom(String sql, ParameterLink parameterLink) throws Exception {
        return iQuery.queryCustom(sql,parameterLink,clazz);
    }

    //批量插入操作的函数入口
    @Override
    public List<T> batchInsert(List<T> objList) throws Exception {
        return iInsert.batchInsert(objList);
    }

    @Override
    public List<T> queryCallHandle(String callSql) throws Exception {
        return iQuery.queryCallHandle(callSql,clazz);
    }


}
